<template>
  <el-drawer
    title="请选择"
    :visible.sync="drawer"
    :direction="direction"
    :before-close="handleClose"
    :append-to-body="true"
    :model="false"
    :wrapperClosable="false"
  >
  <span v-if="data">当前选择: {{ data[0] + ',' + data[1] }} 
    <el-button @click="doPicker" type="danger">确定</el-button></span>
    <el-amap :center="center" :zoom="16" @click="pickerPosition">
        <el-amap-marker v-if="data" :position="data"></el-amap-marker>
      <el-amap-control-geolocation :visible="geoAble" @complete="getLocation" />
    </el-amap>
  </el-drawer>
</template>
<script>

export default {
  name: "LocationPicker",
  props: {
    //默认数据
    location: Object
  },
  data() {
    return {
    center: [116.410474,39.881836],
      drawer: false,
      direction: "rtl",
      data: null,
      geoAble: false
    };
  },
  watch: {
    location: {
      handler(val) {
        if (val) {
         this.drawer = true;
         if(val.data){
             const ll =val.data.split(',');
            this.data = [parseFloat(ll[0]), parseFloat(ll[1])]
         }else{
             this.data = null;
         }
        } else {
          this.drawer = false;
          this.data = null;
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getConfigKey("sys.map.center").then(response => {
        if(response && response.msg){
            const ll = response.msg.split(',');
            this.center = [parseFloat(ll[0]), parseFloat(ll[1])]
            console.log(this.center)
        }
    });
    this.geoAble = window.location.protocol === "https:";
  },
  methods: {
    /** 确认按钮操作 */
    doPicker() {
      this.$emit("picker", this.data[0] + ',' + this.data[1]);
    },
    handleClose() {
        this.drawer = false;
    },
    getLocation(currentPosition) {
        console.log("currentPosition: ", currentPosition);
        this.center = currentPosition;
    },
    pickerPosition(e) {
        this.data = [e.lnglat.lng, e.lnglat.lat];
    }
  },
};
</script>